<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="鱼类名称" prop="fishType">
        <el-input v-model="queryParams.fishType" placeholder="请输入鱼类名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="鱼类科属" prop="fishFamily">
        <el-select v-model="queryParams.fishFamilyId" placeholder="请输入鱼类科属" clearable>
          <el-option v-for="dict in fhFamiliesList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="生长水域" prop="growWaters">
        <el-select v-model="queryParams.growWaters" placeholder="请输入生长水域" clearable>
          <el-option v-for="dict in dict.type.growWaters" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="IUCM状态" prop="iucmStatus">
        <el-select v-model="queryParams.iucmStatus" placeholder="请输入IUCM状态" clearable>
          <el-option v-for="dict in dict.type.iucnstatus" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="crateTime">
        <el-date-picker clearable v-model="queryParams.crateTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['map:fishtype:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['map:fishtype:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['map:fishtype:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['map:fishtype:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fishtypeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="鱼类名称" align="center" prop="fishType" />
      <el-table-column label="鱼类图片" align="center" prop="fishImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.fishImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="鱼类科属" align="center" prop="fishFamily" />

      <el-table-column label="最大重量" align="center">
        <template slot-scope="scope">
          {{ scope.row.maxWeight }} {{ scope.row.maxweightdw }}
        </template>
      </el-table-column>

      <el-table-column label="生长水域" align="center" prop="growWaters" />
      <el-table-column label="IUCM状态" align="center" prop="iucmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.iucnstatus" :value="scope.row.iucmStatus" />
        </template>
      </el-table-column>
      <el-table-column label="平均重量" align="center">
  <template slot-scope="scope">
    {{ scope.row.averageWeight }} {{ scope.row.averageweightdw }}
  </template>
</el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="crateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.crateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['map:fishtype:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['map:fishtype:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleGuide(scope.row)"
            v-hasPermi="['map:fishtype:edit']">垂钓指南</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改鱼类管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="鱼类名称" prop="fishType">
              <el-input v-model="form.fishType" placeholder="请输入鱼类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="鱼类图片" prop="fishImage">
              <image-upload v-model="form.fishImage" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="鱼类科属" prop="fishFamilyId">
              <el-select v-model="form.fishFamilyId" placeholder="请选择鱼类科属" filterable clearable
                @change="onChangefish(form.fishFamilyId)">
                <el-option v-for="dict in fhFamiliesList" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="鱼类简介" prop="fishProfile">
              <el-input type="textarea" :rows="2" v-model="form.fishProfile" placeholder="请输入鱼类简介" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生长水域" prop="growWaters">
              <el-select v-model="form.growWaters" placeholder="请输入生长水域" clearable>
                <el-option v-for="dict in dict.type.growWaters" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="IUCM状态" prop="iucmStatus">
              <el-select v-model="form.iucmStatus" placeholder="请输入IUCM状态" clearable>
                <el-option v-for="dict in dict.type.iucnstatus" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大重量" prop="maxWeight">
              <el-input v-model="form.maxWeight" placeholder="请输入最大重量"
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d+/g, '$1')">
                  <el-select v-model="form.maxweightdw" slot="append" placeholder="请选择" style="width: 80px;">
                    <el-option label="KG" value="KG"></el-option>
                    <el-option label="G" value="G"></el-option>
                  </el-select>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均重量" prop="averageWeight">
              <el-input v-model="form.averageWeight" placeholder="请输入平均重量"
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d+/g, '$1')">
                 <el-select v-model="form.averageweightdw" slot="append" placeholder="请选择" style="width: 80px;">
                    <el-option label="KG" value="KG"></el-option>
                    <el-option label="G" value="G"></el-option>
                  </el-select>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="最大长度" prop="maxLength">
              <el-input v-model="form.maxLength" placeholder="请输入最大长度"
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d+/g, '$1')">
                <template slot="append">CM</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均长度" prop="averageLength">
              <el-input v-model="form.averageLength" placeholder="请输入平均长度"
                oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\.\d{2})\d+/g, '$1')">
                <template slot="append">CM</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>




        <el-row>
          <el-col :span="12">
            <el-form-item label="关联鱼饵" prop="baitIds">
              <el-select v-model="form.baitIds" placeholder="请选择关联鱼饵" filterable multiple clearable size="small">
                <el-option v-for="dict in fishbaitList" :key="dict.id" :label="dict.baitName" :value="dict.id" />
              </el-select>
            </el-form-item>

          </el-col>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                :label="dict.value">{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 垂钓指南对话框 -->
    <el-dialog title="垂钓指南" :visible.sync="guideOpen">
      <el-button type="primary" @click="handleGuideAdd">添加</el-button>
      <el-table style="margin-top: 20px" border stripe :data="guideList" @selection-change="handleSelectionChange">
        <el-table-column prop="topic" label="标题" width="180"></el-table-column>
        <el-table-column prop="descript" label="内容"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope,index">
            <el-button size="mini" type="primary" icon="el-icon-delete" @click="handleGuideUpdate(scope.row)"
              v-hasPermi="['map:fishtype:update']">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete"
              @click="handleGuideDelete(scope.row, scope.$index)" v-hasPermi="['map:fishtype:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 垂钓指南对话框 -->
    <el-dialog :title="!guideForm.id ? '添加垂钓指南': '修改垂钓指南'" :visible.sync="guideUpdateOpen">
      <el-form ref="guideForm" :model="guideForm" :rules="guideRules" label-width="80px">
        <el-form-item label="标题" prop="topic">
          <el-input v-model="guideForm.topic" placeholder="请输入垂钓指南标题" />
        </el-form-item>
        <el-form-item label="内容" prop="descript">
          <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="guideForm.descript" placeholder="请输垂钓指南内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGuideForm">确 定</el-button>
        <el-button @click="cancelGuide">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listFishtype,
    getFishtype,
    delFishtype,
    addFishtype,
    updateFishtype,
    guideList,
    addGuide,
    updateGuide,
    deleteGuide
  } from '@/api/map/fishtype'
  import {
    getFishBait
  } from "@/api/map/fishbait";
  import {
    fhList
  } from "@/api/act/fhFamilies";
  export default {
    name: "Fishtype",
    dicts: ['sys_normal_disable', 'iucnstatus', 'growWaters', 'fishFamily', 'watertype'],
    data() {
      return {
        // 遮罩层
        loading: true,
        fhFamiliesList: {},
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 鱼类管理表格数据
        fishtypeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 垂钓指南是否显示弹出层
        guideOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fishType: null,
          fishImage: null,
          fishFamily: null,
          fishFamilyId: null,
          fishProfile: null,
          maxWeight: null,
          maxLength: null,
          growWaters: null,
          averageDepth: null,
          iucmStatus: null,
          averageWeight: null,
          averageLength: null,
          status: null,
          crateTime: null,
        },
        fishbaitList: {},
        // 表单参数
        form: {},
        guideList: [],
        guideUpdateOpen: false,
        guideForm: {},
        // 表单校验
        rules: {
          fishType: [{
            required: true,
            message: "鱼类名称不能为空",
            trigger: "blur"
          }],
          fishImage: [{
            required: true,
            message: "鱼类不能为空",
            trigger: "blur"
          }],
          fishFamilyId: [{
            required: true,
            message: "鱼类科属不能为空",
            trigger: "blur"
          }],
          growWaters: [{
            required: true,
            message: "生长水域不能为空",
            trigger: "blur"
          }],
          maxWeight: [{
            required: true,
            message: "最大重量不能为空",
            trigger: "blur"
          }],
          baitIds: [{
            required: true,
            message: "关联鱼饵不能为空",
            trigger: "blur"
          }],
        },
        guideRules: {
          topic: [{
            required: true,
            message: '请输入垂钓指南标题',
            trigger: 'blur'
          }],
          descript: [{
            required: true,
            message: '请输入垂钓指南内容',
            trigger: 'blur'
          }],
        },
      };
    },
    created() {
      this.getList();
      this.fhLists();
      var params = {
        status: 0
      }
      getFishBait(params).then(response => {
        this.fishbaitList = response;
      });
    },
    methods: {
      /** 查询鱼类管理列表 */
      getList() {
        this.loading = true;
        listFishtype(this.queryParams).then(response => {
          this.fishtypeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      //查询鱼类科属列表
      fhLists() {
        fhList().then(response => {
          this.fhFamiliesList = response
          console.log(this.fhFamiliesList, "1111")
        })
      },
      onChangefish(componentId, index) {
        console.log(componentId, "222222")
        var isshw = 0
        if (!componentId) {
          isshw = 1
        } else {
          const selectedFish = this.fhFamiliesList.find(item => item.id === componentId)
          console.log(selectedFish, "selectedFish")
          if (selectedFish) {
            this.form.fishFamily = selectedFish.name
          } else {
            this.form.fishFamily = ""
          }
        }
        if (isshw == 1) {
          this.form.fishFamily = "";
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          fishType: null,
          fishImage: null,
          fishFamily: null,
          fishFamilyId: null,
          fishProfile: null,
          maxWeight: null,
          maxLength: null,
          growWaters: null,
          averageDepth: null,
          iucmStatus: null,
          averageWeight: null,
          averageLength: null,
          status: null,
          createBy: null,
          crateTime: null,
          updateBy: null,
          updateTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加鱼类管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getFishtype(id).then(response => {
          this.form = response.data;
          if (this.form.baitIds) {
            this.form.baitIds = this.form.baitIds.split(",").map(Number);
          }
          this.open = true;
          this.title = "修改鱼类管理";
        });
      },
      /** 垂钓指南方法 */
      handleGuide(row) {
        this.guideForm.fishId = row.id;
        guideList(row.id).then(res => {
          this.guideList = res.data;
        })
        this.guideOpen = true;

      },
      /** 提交按钮 */
      submitForm() {

        if (!/^\d+(\.\d{1,2})?$/.test(this.form.averageWeight)) {
          this.$modal.msgSuccess("请输入合法的数值，最多两位小数");
          return false
        }

        if (!/^\d+(\.\d{1,2})?$/.test(this.form.maxWeight)) {
          this.$modal.msgSuccess("请输入合法的数值，最多两位小数");
          return false
        }

        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.baitIds = this.form.baitIds.toString()
            if (this.form.id != null) {
              updateFishtype(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addFishtype(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除鱼类管理编号为"' + ids + '"的数据项？').then(function() {
          return delFishtype(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('map/fishtype/export', {
          ...this.queryParams
        }, `fishtype_${new Date().getTime()}.xlsx`)
      },


      // 取消按钮
      cancelGuide() {
        this.guideUpdateOpen = false;
        this.resetGuide();
      },
      // 表单重置
      resetGuide() {
        this.guideForm = {
          fishId: this.guideForm.fishId,
          id: null,
          topic: null,
          descript: null,
        };
        this.resetForm("form");
      },

      /** 提交按钮 */
      submitGuideForm() {
        this.$refs["guideForm"].validate(valid => {
          if (valid) {
            if (this.guideForm.id != null) {
              updateGuide(this.guideForm).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.guideUpdateOpen = false;
                this.handleGuide({
                  id: this.guideForm.fishId
                })
              });
            } else {
              addGuide(this.guideForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.guideUpdateOpen = false;
                this.handleGuide({
                  id: this.guideForm.fishId
                })
              });
            }
          }
        });
      },
      /**
       * 增加垂钓指南按钮
       * */
      handleGuideAdd() {
        this.resetGuide()
        this.guideUpdateOpen = true;
      },

      handleGuideUpdate(row) {
        this.guideForm.topic = row.topic;
        this.guideForm.descript = row.descript;
        this.guideForm.id = row.id;
        this.guideUpdateOpen = true;
      },
      /** 删除垂钓指南按钮操作 */
      handleGuideDelete(row, index) {

        this.$modal.confirm('是否确认删除垂钓指南为"' + row.topic + '"的数据项？').then(() => {
          return deleteGuide(row.id);
        }).then(() => {
          this.guideList.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
    }
  };
</script>
